using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SuCasa.Infrastructure;

namespace SuCasa.DataAccess{
    public interface IMemberRepository {
        IEnumerable<Member> All { get; }
        bool AddMember(Member member);
        bool AddCourse(int memberId, Course course);
        IEnumerable<Member> GetMembers(string query);
        Member GetMemberBy(Func<Member, bool> func);
        void Delete(int id);
        IEnumerable<MemberType> GetMemberTypes();
        IEnumerable<Member> GetAll();
    }

    public class MemberRepository : IMemberRepository{
        readonly SuCasaDbContext _context;

        public MemberRepository(SuCasaDbContext context){
            _context = context;
        }

        public IEnumerable<Member> All{
            get{
                var result = _context.Members.Include("Courses").Include("Assignments").ToList();
                return result;
            }
        }

        public bool AddMember(Member member){
            
            if (member.MemberId == 0){
                _context.Members.Add(member);
            }
            else
            {
                _context.Members.Attach(member);
                _context.Entry(member).State = EntityState.Modified;
                
            }
            return _context.SaveChanges() > 0;
        }

        public IEnumerable<Member> GetAll()
        {
            return _context.Members.Include("Courses").Include("Assignments").ToList();
        }

        public bool AddCourse(int memberId, Course course)
        {
            var member = _context.Members.Include("Courses").Include("Assignments").SingleOrDefault(x => x.MemberId == memberId);
            member.Courses.Add(course);

            _context.SaveChanges();
            return true;

        }

        public IEnumerable<Member> GetMembers(string query){
            return _context.Members.Include("Courses").Include("Assignments").Where(x => x.FirstName.Contains(query) || x.MiddleName.Contains(query) || x.LastName.Contains(query));
        }

        public Member GetMemberBy(Func<Member, bool> func){

            return _context.Members.Include("Courses").Include("Assignments").SingleOrDefault(func);
        }

        public void Delete(int id){
            var member = _context.Members.Single(x => x.MemberId == id);
            _context.Members.Remove(member);
            _context.SaveChanges();
        }

        public IEnumerable<MemberType> GetMemberTypes(){
            var result = _context.MemberTypes.Where(x => true);
            return result;
        }
    }
}